import 'ref.dart';
import 'helpers/tools.dart';

/// 代理某一个对象的属性
/// 会保持响应
class RefKey<T> {
  /// [ref] Ref实例
  Ref ref;

  /// [key]Map的key或者List的下标
  dynamic key;

  /// 由key分割得到 ['info', 'arr', 0]
  late List<dynamic> _getKeylist;

  RefKey(this.ref, this.key) {
    if (!(ref.value is List || ref.value is Map)) {
      print('app error: RefKey 调用代理的Ref对象的值类型必须是List或者Map！');
      throw TypeError();
    }
    _getKeylist = getKeylist(key);
  }

  T get value {
    dynamic res = ref.value;
    _getKeylist.forEach((ele) {
      res = res?[ele];
    });
    return res;
  }

  set value(T data) {
    dynamic res = ref.value;
    for (var i = 0; i < _getKeylist.length; i++) {
      dynamic ele = _getKeylist[i];
      if (i == _getKeylist.length - 1) {
        res?[ele] = data;
      } else {
        res = res?[ele];
      }
    }
    ref.value = ref;
  }
}
